import axios from 'axios'

var http = axios.create({
    timeout: 5000,
    baseURL: process.env.VUE_APP_BASE_API,
    validateStatus(status) {
        switch (status) {
        case 400:
            // Message.error('请求出错')
            break
        case 401:
            // Message.warning({
            //     message: '授权失败，请重新登录'
            // })
            // store.commit('LOGIN_OUT')
            // setTimeout(() => {
            //     window.location.reload()
            // }, 1000)
            return
        case 403:
            // Message.warning({
            //     message: '拒绝访问'
            // })
            break
        case 404:
            // Message.warning({
            //     message: '请求错误,未找到该资源'
            // })
            break
        case 500:
            // Message.warning({
            //     message: '服务端错误'
            // })
            break
        }
        return status >= 200 && status < 300
    }
})

// 添加请求拦截器
http.interceptors.request.use(
    config => {
        // do something before request is sent
    
        // if (store.getters.token) {
          // let each request carry token
          // ['X-Token'] is a custom headers key
          // please modify it according to the actual situation
        //   config.headers['X-Token'] = getToken()
        // }
        return config
      },
      error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
      }
)

// 响应拦截器即异常处理
http.interceptors.response.use(
    response => {
        const resp = response.data
        if (resp.code === 200)
            return resp
        else
            return Promise.reject(resp)
    },
    error => {
        if (error && error.response) {
            error.message = '连接服务器失败'
        }
        return Promise.reject(error)
    }
)

export default http